package com.ufo.store.management.ui.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.adapter.MemberRecyclerViewAdapter;
import com.ufo.store.management.database.DatabaseManager;
import com.ufo.store.management.entity.Member;
import com.ufo.store.management.ui.activity.MemberConsumptionActivity;
import com.ufo.store.management.ui.activity.MemberEditActivity;
import com.ufo.store.management.utils.PinyinComparator;
import com.ufo.store.management.utils.Utils;
import com.ufo.store.management.widget.PtrClassicFrameLayout.LoadingFooter;
import com.ufo.store.management.widget.PtrClassicFrameLayout.LoadingHeader;
import com.ufo.store.management.widget.view.SideBar;
import com.ufo.store.management.widget.dialog.DeleteItemDialog;
import com.ufo.store.management.widget.recyclerview.EndlessRecyclerOnScrollListener;

import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

import static android.app.Activity.RESULT_OK;

/**
 *  作者：taoli on 2017/2/28 0028 11:08
 *  
 */
public class MemberListFragment extends BaseLazyFragment implements Handler.Callback {
    public static final String TAG = MemberListFragment.class.getSimpleName();
    private final int ACTIVITY_RESULT_MEMBER_DETAIL = 100;
    private final int LOAD_DATA_FINISH = 1;
    private final int REFRESH_DATA_FINISH = 2;

    private RelativeLayout mProcessTipLy = null;
    private LinearLayout mGetMemberFailTipLy = null;
    private TextView mMemberFailTipTv = null;

    private Handler mHandler = null;
    private SideBar mPinyinSideBar = null;
    private TextView mCharDialog = null;

    private RecyclerView mMemberRecyclerView = null;
    private MemberRecyclerViewAdapter mMemberRecyclerViewAdapter = null;
    private PtrClassicFrameLayout mPtrFrame;

    private int mStartIndex = -1;
    private int mMaxMemberCount = -1;

    private Object mLock = new Object();
    private boolean bCanRefresh = true;

    private PinyinComparator mPinyinComparator = null;

    private DeleteItemDialog mDeleteItemDialog;

    private int mPosition = -1;

    private String mMemberPointValue = "0";

    private List<String> mMemberPointValueList;

    private int ListStyle;

    private boolean mIsTitleLlHided = false;
    private boolean mCanLoadMore = true;

    private int SortMode = -1;     // 0:姓名升序   1：姓名降序    2：积分升序  3：积分降序    4：消费升序     5：消费降序


    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case REFRESH_DATA_FINISH:
                if (mMemberRecyclerViewAdapter != null) {
                    final List<Member> data = (List<Member>) msg.obj;
                    mPtrFrame.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mPtrFrame.refreshComplete();
                            mMemberRecyclerViewAdapter.setData(data);
                            mMemberRecyclerViewAdapter.notifyDataSetChanged();
                        }
                    }, 0);
                }
                break;
            case LOAD_DATA_FINISH:
                if (mMemberRecyclerViewAdapter != null) {
                    final List<Member> data = (List<Member>) msg.obj;
                    mPtrFrame.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mPtrFrame.refreshComplete();
                            mMemberRecyclerViewAdapter.insertData(data);
                            mMemberRecyclerViewAdapter.notifyItemRangeInserted(mStartIndex - data.size(), data.size());
                        }
                    }, 0);
                }
                break;
            default:
                break;
        }
        return false;
    }

    /**
     * 布局文件ID
     *
     * @return
     */
    protected int getLayoutId() {
        return R.layout.fragment_member_list;
    }

    /**
     * 初始化数据
     */
    protected void initData() {
        loaded();
        mHandler = new Handler(this);
        mPinyinComparator = new PinyinComparator();
        if (mPosition > 0 && mPosition < mMemberPointValueList.size())
            mMemberPointValue = mMemberPointValueList.get(mPosition);
    }

    protected void onFirstUserVisible() {
        getMemberInfoList(true);
    }

    protected void onUserVisible() {
    }

    protected void onFirstUserInvisible() {

    }

    protected void onUserInvisible() {

    }

    /**
     * 初始化组件
     */
    protected void initViewData(View entryView) {
        mProcessTipLy = (RelativeLayout) entryView.findViewById(R.id.progress_tip_ly);
        mGetMemberFailTipLy = (LinearLayout) entryView.findViewById(R.id.get_member_fail_tip_ly);
        mGetMemberFailTipLy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getMemberInfoList(true);
            }
        });
        mMemberFailTipTv = (TextView) entryView.findViewById(R.id.get_member_list_fail_tv);

        mPtrFrame = (PtrClassicFrameLayout) entryView.findViewById(R.id.ptr);
        mPtrFrame.setLastUpdateTimeRelateObject(this);
        mPtrFrame.disableWhenHorizontalMove(true);
        mPtrFrame.setPtrHandler(ptrDefaultHandler2);//设置下拉上拉监听

        //设置头尾刷新布局（以下四步骤部必须按照顺序设置，否则无效）
        LoadingFooter ptrLoadUIHandler = new LoadingFooter(getContext());
        mPtrFrame.setFooterView(ptrLoadUIHandler);
        mPtrFrame.addPtrUIHandler(ptrLoadUIHandler);
        //添加头部处理功能
        LoadingHeader ptrRefreshUIHandler = new LoadingHeader(getContext());
        mPtrFrame.addPtrUIHandler(ptrRefreshUIHandler);
        mPtrFrame.setHeaderView(ptrRefreshUIHandler);

        mPinyinSideBar = (SideBar) entryView.findViewById(R.id.sidrbar);
        mCharDialog = (TextView) entryView.findViewById(R.id.dialog);
        mPinyinSideBar.setTextView(mCharDialog);
        // 设置右侧触摸监听
        mPinyinSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = mMemberRecyclerViewAdapter.getPositionForSection(s.charAt(0));
                if (ListStyle == 1) {
                    RecyclerView.LayoutManager linearLayoutManager = mMemberRecyclerView.getLayoutManager();
                    linearLayoutManager.scrollToPosition(position);
                }
            }
        });


        mMemberRecyclerView = (RecyclerView) entryView.findViewById(R.id.member_recyclerview);
        if (ListStyle == 1) {
            mMemberRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            mPinyinSideBar.setVisibility(View.VISIBLE);
        } else if (ListStyle == 2) {
            mMemberRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
            mPinyinSideBar.setVisibility(View.GONE);
        }
        mMemberRecyclerViewAdapter = new MemberRecyclerViewAdapter(getActivity(), ListStyle);
        mMemberRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mMemberRecyclerView.setHasFixedSize(true);
        mMemberRecyclerView.setAdapter(mMemberRecyclerViewAdapter);
        mMemberRecyclerViewAdapter.setOnClickListener(new MemberRecyclerViewAdapter.OnClickListener() {
            @Override
            public void onDetailClick(int position) {
                Member memberInfo = mMemberRecyclerViewAdapter.getItem(position);
                Intent toIntent = new Intent(getActivity(), MemberConsumptionActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("MemberInfo", memberInfo);
                toIntent.putExtras(bundle);
                startActivity(toIntent);

                int i = mMemberRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mMemberRecyclerViewAdapter.setLongPressedIndex(-1);
                    mMemberRecyclerViewAdapter.notifyItemChanged(i, "menu");
                }
            }

            @Override
            public void onDeleteClick(int position) {
                showDeleteItemDialog(position);
                int i = mMemberRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mMemberRecyclerViewAdapter.setLongPressedIndex(-1);
                    mMemberRecyclerViewAdapter.notifyItemChanged(i, "menu");
                }
            }

            @Override
            public void onItemClick(View v, int position) {
                Member memberInfo = mMemberRecyclerViewAdapter.getItem(position);
                Intent toIntent = new Intent(getActivity(), MemberEditActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("MemberInfo", memberInfo);
                toIntent.putExtras(bundle);

                // Now we can start the Activity, providing the activity options as a bundle
                /**
                 * Now create an {@link android.app.ActivityOptions} instance using the
                 * {@link ActivityOptionsCompat#makeSceneTransitionAnimation(Activity, Pair[])} factory
                 * method.
                 */
                //Pair<View, String> pContent = Pair.create(v.findViewById(R.id.content_ll), MemberEditActivity.VIEW_NAME_HEADER_TITLE);
                Pair<View, String> pImage = Pair.create(v.findViewById(R.id.member_icon_iv), MemberEditActivity.VIEW_NAME_HEADER_IMAGE);
                @SuppressWarnings("unchecked")
//                ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(
//                        getActivity(),
//                        // Now we provide a list of Pair items which contain the view we can transitioning
//                        // from, and the name of the view it is transitioning to, in the launched activity
//                        pImage, pContent);
                        ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(
                        getActivity(),
                        // Now we provide a list of Pair items which contain the view we can transitioning
                        // from, and the name of the view it is transitioning to, in the launched activity
                        pImage);
//                    @SuppressWarnings("unchecked")
//                    ActivityOptions activityOptions = ActivityOptions.makeSceneTransitionAnimation(
//                            getActivity(),
//                            // Now we provide a list of Pair items which contain the view we can transitioning
//                            // from, and the name of the view it is transitioning to, in the launched activity
//                            v.findViewById(R.id.member_icon_iv), MemberEditActivity.VIEW_NAME_HEADER_IMAGE);
                startActivityForResult(toIntent, ACTIVITY_RESULT_MEMBER_DETAIL, activityOptions.toBundle());

                int i = mMemberRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mMemberRecyclerViewAdapter.setLongPressedIndex(-1);
                    mMemberRecyclerViewAdapter.notifyItemChanged(i, "menu");
                }
            }

            @Override
            public void onItemLongClick(View v, int position) {
                int i = mMemberRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mMemberRecyclerViewAdapter.setLongPressedIndex(position);
                    mMemberRecyclerViewAdapter.notifyItemChanged(i, "menu");
                    mMemberRecyclerViewAdapter.notifyItemChanged(position, "menu");
                } else {
                    mMemberRecyclerViewAdapter.setLongPressedIndex(position);
                    mMemberRecyclerViewAdapter.notifyItemChanged(position, "menu");
                }
            }

            @Override
            public void onMenuClick(View v, int position) {
                int i = mMemberRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mMemberRecyclerViewAdapter.setLongPressedIndex(position);
                    mMemberRecyclerViewAdapter.notifyItemChanged(i, "menu");
                    mMemberRecyclerViewAdapter.notifyItemChanged(position, "menu");
                } else {
                    mMemberRecyclerViewAdapter.setLongPressedIndex(position);
                    mMemberRecyclerViewAdapter.notifyItemChanged(position, "menu");
                }
            }

            @Override
            public void onMaskClick(View v, int position) {
                int i = mMemberRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mMemberRecyclerViewAdapter.setLongPressedIndex(-1);
                    mMemberRecyclerViewAdapter.notifyItemChanged(i, "menu");
                }
            }
        });

        mMemberRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mMemberListGetProcessListener != null) {
                    mMemberListGetProcessListener.onMemberListViewTouchEvent(event);
                }
                return false;
            }
        });

        mMemberRecyclerView.addOnScrollListener(mOnScrollListener);
    }

    private PtrDefaultHandler2 ptrDefaultHandler2 = new PtrDefaultHandler2() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return !mIsTitleLlHided && PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            getMemberInfoList(true);
        }

        @Override
        public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
            return false && PtrDefaultHandler2.checkContentCanBePulledUp(frame, content, footer);
        }

        @Override
        public void onLoadMoreBegin(PtrFrameLayout frame) {
            mPtrFrame.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPtrFrame.refreshComplete();
                }
            }, 0);
        }
    };

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {
        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            if (mCanLoadMore) {
                getMemberInfoList(false);
            }
        }
    };

    /**
     * @desc 2 个定时器同时动画滚动 item 图片
     * @author taoli
     * @time 2017/8/25 0025
     */
    private boolean bShow[] = {true, true};
    private int lastExhibitPos[] = {-1, -1};
    private CountDownTimer firstVerticalScrollCountDownTimer;
    private CountDownTimer secondVerticalScrollCountDownTimer;
    private void startAnimateExhibit() {
        if (firstVerticalScrollCountDownTimer == null) {
            firstVerticalScrollCountDownTimer = new CountDownTimer(Long.MAX_VALUE, 4500) {
                @Override
                public void onTick(long millisUntilFinished) {
                    int lastVisibleItemPosition = getRecyclerViewLastVisibleItemPosition(mMemberRecyclerView);
                    int result = lastVisibleItemPosition - new java.util.Random().nextInt(8);
                    if (result == lastExhibitPos[1] && bShow[0]) {
                        return;
                    }
                    if (result >= 0 && result <= lastVisibleItemPosition) {
                        if (bShow[0]) {
                            bShow[0] = false;
                            lastExhibitPos[0] = result;
                            mMemberRecyclerViewAdapter.notifyItemChanged(lastExhibitPos[0], "exhibit");
                        } else {
                            bShow[0] = true;
                            mMemberRecyclerViewAdapter.notifyItemChanged(lastExhibitPos[0], "recovery");
                        }
                    }
                }

                @Override
                public void onFinish() {

                }
            }.start();
        }
        if (secondVerticalScrollCountDownTimer == null) {
            secondVerticalScrollCountDownTimer = new CountDownTimer(Long.MAX_VALUE, 3500) {
                @Override
                public void onTick(long millisUntilFinished) {
                    int lastVisibleItemPosition = getRecyclerViewLastVisibleItemPosition(mMemberRecyclerView);
                    int result = lastVisibleItemPosition - new java.util.Random().nextInt(8);
                    if (result == lastExhibitPos[0] && bShow[1]) {
                        return;
                    }
                    if (result >= 0 && result <= lastVisibleItemPosition) {
                        if (bShow[1]) {
                            bShow[1] = false;
                            lastExhibitPos[1] = result;
                            mMemberRecyclerViewAdapter.notifyItemChanged(lastExhibitPos[1], "exhibit");
                        } else {
                            bShow[1] = true;
                            mMemberRecyclerViewAdapter.notifyItemChanged(lastExhibitPos[1], "recovery");
                        }
                    }
                }

                @Override
                public void onFinish() {

                }
            }.start();
        }
    }

    /**
     * @desc 获取 RecyclerView 最后一个可见 Item 的 position 索引，以便于计算在屏幕范围内需要随机滚动的 Item 索引
     * @author taoli
     * @time 2017/8/30 0030
     */
    private int getRecyclerViewLastVisibleItemPosition(RecyclerView recyclerView) {
        int lastVisibleItemPosition = 0;
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager instanceof LinearLayoutManager) {
            lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
        } else if (layoutManager instanceof GridLayoutManager) {
            lastVisibleItemPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
            int[] lastPositions = new int[staggeredGridLayoutManager.getSpanCount()];
            staggeredGridLayoutManager.findLastVisibleItemPositions(lastPositions);
            lastVisibleItemPosition = Utils.findMax(lastPositions);
        }
        return lastVisibleItemPosition;
    }

    /**
     * @desc 动态设置 RecyclerView 的布局分割，是列表布局还是网格瀑布布局
     * @author taoli
     * @time 2017/8/30 0030
     */
    public void setStyle(int s) {
        ListStyle = s;
        mMemberRecyclerViewAdapter.setStyle(ListStyle);
        if (s == 1) {
            mMemberRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            mPinyinSideBar.setVisibility(View.VISIBLE);
        } else if (s == 2) {
            mMemberRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
            mPinyinSideBar.setVisibility(View.GONE);
        }
    }

    /**
     * @desc  设置是否可以下拉刷新
     * @author taoli
     * @time 2017/8/30 0030
     */
    public void setTitleIsHided(boolean is){
        mIsTitleLlHided = is;
    }

    public void setMemberListStyle(int s) {
        ListStyle = s;
    }

    public void setMemberSearchSortMode(int m) {
        SortMode = m;
        if (mPtrFrame != null) {
            getMemberInfoList(true);
        }
    }

    public void setPosition(int p) {
        this.mPosition = p;
    }

    public void setMemberPointList(List<String> list) {
        this.mMemberPointValueList = list;
    }

    private int mDeletePosition = -1;

    public void showDeleteItemDialog(final int positionMember) {
        if (mDeleteItemDialog == null) {
            mDeleteItemDialog = new DeleteItemDialog(getActivity());
            Window window = mDeleteItemDialog.getWindow(); //得到对话框
            window.setWindowAnimations(R.style.dialog_anim_center_style); //设置窗口弹出动画
        }
        final Member memberInfo = mMemberRecyclerViewAdapter.getItem(positionMember);
        mDeleteItemDialog.setTips(memberInfo.memberName.trim());
        mDeleteItemDialog.setItemClickListener(new DeleteItemDialog.OnItemClick() {
            @Override
            public void onItemClick(int position) {
                if (position == 0) {
                    //取消
                } else if (position == 1) {
                    //确定
                    mDeletePosition = positionMember;
                    new DeleteMemberInfoTask().execute(memberInfo.memberId);
                }
            }
        });
        mDeleteItemDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });
        mDeleteItemDialog.show();
    }

    private synchronized void getMemberInfoList(boolean headerOrFooter) {
        if (getActivity() != null && getActivity().isFinishing()) {
            return;
        }
        if (!bCanRefresh)
            return;

        new GetMemberInfoListTask(headerOrFooter).execute();
    }

    private class GetMemberInfoListTask extends AsyncTask<Void, Void, List<Member>> {
        private boolean mHeaderOrFooter;

        public GetMemberInfoListTask(boolean headerOrFooter) {
            mHeaderOrFooter = headerOrFooter;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            bCanRefresh = false;
        }

        @Override
        protected List<Member> doInBackground(Void... params) {
            if (getActivity() != null && getActivity().isFinishing()) {
                return null;
            }

            List<Member> result = null;
            if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                if (mHeaderOrFooter == true) {
                    mStartIndex = 0;
                    // 请求会员最大数量
                    mMaxMemberCount = DatabaseManager.getMemberCountFromSqlServer(getActivity(), mMemberPointValue);
                }
                result = DatabaseManager.getMemberInfoListFromSqlServer(getActivity(), mStartIndex, BarApplication.pagesize, mMaxMemberCount, 0, SortMode, mMemberPointValue);
            } else {
                if (mHeaderOrFooter == true) {
                    mStartIndex = 0;
                }
                result = DatabaseManager.getMemberInfoListFromLocal(getActivity(), mStartIndex, BarApplication.pagesize, 0, SortMode, mMemberPointValue);
            }
            if (result != null) {
                mStartIndex = mStartIndex + result.size();
                //Collections.sort(result, mPinyinComparator);    //数据库已排序
            }
            return result;
        }

        @Override
        protected void onPostExecute(final List<Member> result) {
            super.onPostExecute(result);
            if (getActivity() != null && getActivity().isFinishing()) {
                return;
            }

            if (result != null) {
                synchronized (mLock) {
                    if (mHeaderOrFooter == true) {
                        mCanLoadMore = true;
                    }

                    if (mStartIndex == 0) {
                        //mMemberRecyclerView.setVisibility(View.GONE);
                        mPinyinSideBar.setVisibility(View.GONE);
                        //mProcessTipLy.setVisibility(View.GONE);
                        mGetMemberFailTipLy.setVisibility(View.VISIBLE);
                        mMemberFailTipTv.setText("无会员");
                    } else {
                        //mMemberRecyclerView.setVisibility(View.VISIBLE);
                        if (ListStyle == 1) {
                            mPinyinSideBar.setVisibility(View.VISIBLE);
                        } else if (ListStyle == 2) {
                            mPinyinSideBar.setVisibility(View.GONE);
                        }
                        //mProcessTipLy.setVisibility(View.GONE);
                        mGetMemberFailTipLy.setVisibility(View.GONE);
                    }

                    if (mMemberListGetProcessListener != null) {
                        mMemberListGetProcessListener.onMemberIndexProcessFinish(mMaxMemberCount, mPosition);
                    }
                    if (mMemberPointValue.equals("0") && mMemberListGetProcessListener != null) {
                        mMemberListGetProcessListener.onMemberMaxIndexProcessFinish(mMaxMemberCount);
                    }

                    int count = result.size();
                    if (count < BarApplication.pagesize) {
                        mCanLoadMore = false;
                    }
                    if( count != 0 && mHeaderOrFooter){
                        startAnimateExhibit();
                    }
                    if (mHeaderOrFooter) {
                        Message _Msg = mHandler.obtainMessage(REFRESH_DATA_FINISH, result);
                        mHandler.sendMessage(_Msg);
                    } else if (!mHeaderOrFooter) {
                        Message _Msg = mHandler.obtainMessage(LOAD_DATA_FINISH, result);
                        mHandler.sendMessage(_Msg);
                    }
                }
            }

            bCanRefresh = true;
        }
    }

    private class DeleteMemberInfoTask extends AsyncTask<String, Void, String> {
        public DeleteMemberInfoTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            String memberId = params[0];
            long row = -1;
            if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                row = DatabaseManager.deleteMemberInfoFromSqlServer(getActivity(), memberId);
            } else {
                row = DatabaseManager.deleteMemberInfoFromLocal(getActivity(), memberId);
            }
            return String.valueOf(row);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result.equals("1")) {
                mMemberRecyclerViewAdapter.removeData(mDeletePosition);
                mMemberRecyclerViewAdapter.notifyItemRemoved(mDeletePosition);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTIVITY_RESULT_MEMBER_DETAIL) {
            if (resultCode == RESULT_OK) {
                getMemberInfoList(true);
            }
        }
    }

    private MemberListGetProcessListener mMemberListGetProcessListener = null;

    public void setMemberListGetProcessListener(MemberListGetProcessListener listener) {
        mMemberListGetProcessListener = listener;
    }

    public interface MemberListGetProcessListener {
        public void onMemberMaxIndexProcessFinish(int maxMemberIndex);

        public void onMemberIndexProcessFinish(int maxMemberCountByPoint, int position);

        public void onMemberListViewTouchEvent(MotionEvent event);
    }
}
